#include "networkinterface.h"

QTcpServer NetworkInterface::GameServer;

void NetworkInterface::StartServer()
{
    GameServer.listen(QHostAddress::Any, 4268);
}

void NetworkInterface::StopServer()
{
    GameServer.close();
}

NetworkInterface::NetworkInterface(QTcpSocket *ConnectedSocket)
{
    Socket = ConnectedSocket;
    State = WAITING_FOR_HELLO;
    connect(Socket,SIGNAL(readyRead()),this,SLOT(ReceivedData()));
    Socket->write("Hello Minion\n");
}

bool NetworkInterface::ReceivedLobbyData(QString data)
{
    if(data.startsWith("Switch to team "))
        emit TeamChanged(data.right(1).toInt());
}

void NetworkInterface::ReceivedData()
{
    bool Fail = false;
    QString data(Socket->readLine());
    data = data.trimmed();

    switch(State)
    {
    case WAITING_FOR_HELLO:
        if(data == "Hello Minion Server")
        {
            Socket->write("Who are you?\n");
            State = WAITING_FOR_NAME;
        }
        else Fail = true;
        break;
    case WAITING_FOR_NAME:
        if(data.startsWith("I am "))
        {
            State = LOBBY_READY;
            emit NameChanged(data.mid(5));
        }
        else Fail = true;
        break;
    case LOBBY_READY:
        Fail = ReceivedLobbyData(data);
        break;
    }

    if(Fail)
    {
        Socket->disconnect();
        emit Disconnected(this);
    }
}
